package switchviz.recording;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.jdom.JDOMException;

import switchviz.core.ResourceManager;

public class RecordTree extends JPanel
{

	/**
	 * 
	 */
	private static final long serialVersionUID = -1463298424930587383L;
	private JTree _jtree = null;
	private DefaultTreeModel _treemodel = null;
	
	public RecordTree() throws JDOMException, IOException
	{
		initializeStructure();
		initializeGUI();
	}
	
	public JTree getTree()
	{
		return _jtree;
	}
	
	public void reload() throws JDOMException, IOException
	{
		//_jtree.setRootVisible(true);
		_treemodel.setRoot(null);
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("records");
		_treemodel.setRoot(root);
		fillInRecords(root);
		_treemodel.reload(root);
		//_jtree.setRootVisible(false);
	}
	
	private void initializeStructure() throws JDOMException, IOException
	{
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("records");
		_jtree = new JTree(root);
		_treemodel = (DefaultTreeModel)_jtree.getModel();
		fillInRecords(root);
		
	}
	
	private void fillInRecords(DefaultMutableTreeNode root) throws JDOMException, IOException
	{
		List<RecordDataModel> reclist = RecordPersistence.getInstance().getRecordList();
		for(RecordDataModel rdm : reclist)
		{
			DefaultMutableTreeNode child = new DefaultMutableTreeNode(rdm);
			_treemodel.insertNodeInto(child, root, root.getChildCount());
			fillInSignals(child, rdm.getFolder());
		}
	}
	
	private void fillInSignals(DefaultMutableTreeNode parent, File folder)
	{
		
		List<File> filelist = RecordPersistence.getInstance().getFileList(folder);
		for(File file : filelist)
		{
			_treemodel.insertNodeInto(new DefaultMutableTreeNode(file.getName()), parent, parent.getChildCount());
		}
	}
	
	private void initializeGUI()
	{
		this.setLayout(ResourceManager.getInstance().getBorderLayout());
		_jtree.expandRow(0);
		_jtree.addSelectionRow(0);
	    JScrollPane scrollpane = new JScrollPane(_jtree);
        this.add(scrollpane, BorderLayout.CENTER);
        this.setPreferredSize(new Dimension(400, 400));
        _jtree.setRootVisible(false);
	}
}
